package startup

import (
	"context"
	"gitee.com/kelvins-io/kelvins"
	"gitee.com/kelvins-io/kelvins-template/proto/kelvins_template_proto/kelvins_template"
	"gitee.com/kelvins-io/kelvins-template/server"
	healthpb "google.golang.org/grpc/health/grpc_health_v1"
	"net/http"
	"time"

	"gitee.com/kelvins-io/kelvins-template/http_server"
	"github.com/grpc-ecosystem/grpc-gateway/runtime"
	"google.golang.org/grpc"
)

// RegisterGRPCServer 此处注册pb的Server
func RegisterGRPCServer(grpcServer *grpc.Server) error {
	// 在这里将proto生成pb.go里面的server注册到grpcServer
	kelvins_template.RegisterYourServiceServer(grpcServer, server.NewYourServer())
	return nil
}

// RegisterGateway 此处注册pb的Gateway
func RegisterGateway(ctx context.Context, gateway *runtime.ServeMux, endPoint string, dopts []grpc.DialOption) error {
	// 在这里将proto生成的pb.gw.go里面的ServiceHandlerFromEndpoint注册进gateway *runtime.ServeMux
	if err := kelvins_template.RegisterYourServiceHandlerFromEndpoint(ctx, gateway, endPoint, dopts); err != nil {
		return err
	}
	return nil
}

// RegisterHttpRoute 此处注册http接口
func RegisterHttpRoute(serverMux *http.ServeMux) error {
	serverMux.HandleFunc("/swagger/", http_server.SwaggerHandler)
	return nil
}

const (
	healthCheckSleep = 1 * time.Minute
)

func RegisterGRPCHealthHandle(health *kelvins.GRPCHealthServer) {
	// first set
	health.SetServingStatus("", healthpb.HealthCheckResponse_SERVING)
	health.SetServingStatus("kelvins_template.YourService", healthpb.HealthCheckResponse_SERVING)
	ticker := time.NewTicker(healthCheckSleep)
	defer ticker.Stop()
	for {
		select {
		case <-ticker.C:
			health.SetServingStatus("", healthpb.HealthCheckResponse_SERVING)
			health.SetServingStatus("kelvins_template.YourService", healthpb.HealthCheckResponse_SERVING)
		case <-kelvins.AppCloseCh:
			health.SetServingStatus("", healthpb.HealthCheckResponse_NOT_SERVING)
			health.SetServingStatus("kelvins_template.YourService", healthpb.HealthCheckResponse_NOT_SERVING)
			return
		}
	}
}
